package com.example.capsule_chat0322.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.adapter.FriendListAdapter;
import com.example.capsule_chat0322.adapter.FriendMoreFunctionAdapter;
import com.example.capsule_chat0322.bean.FriendApplyBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.layout.ItemGroup;
import com.example.capsule_chat0322.request.UserInfoRequest;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhuzhiming
 * @Date 2022/5/1 16:59
 */
public class UserInfoActivity extends AppCompatActivity {

    private ItemGroup user_nickname;
    private ItemGroup user_id;
    private ItemGroup user_sign;
    private ItemGroup user_sex;
    private ItemGroup user_age;
    private ItemGroup user_hobby;
    private ItemGroup user_email;
    private ImageView user_avatar;
    private TextView title;
    private TextView like;
    private Button make_friend;
    private Button one_to_one_chat;
    private final int USER_INFO_CODE = 0;
    private static final int UPDATE_INFO_CODE = 2;
    private static final int UPDATE_Friend_CODE = 3;
    private String friendApply;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_info);
        initView();
    }

    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initView() {

        user_nickname = findViewById(R.id.user_nickname);
        user_id = findViewById(R.id.user_mark);
        user_avatar = findViewById(R.id.user_avatar);
        user_nickname = findViewById(R.id.user_nickname);
        user_sign = findViewById(R.id.user_sign);
        user_sex = findViewById(R.id.user_sex);
        user_age = findViewById(R.id.user_age);
        user_hobby = findViewById(R.id.user_hobby);
        user_email = findViewById(R.id.user_email);
        title = findViewById(R.id.title);
        like = findViewById(R.id.like);
        make_friend = findViewById(R.id.make_friend);
        one_to_one_chat = findViewById(R.id.one_to_one_chat);

        int senderId = getIntent().getIntExtra("senderId", 0);

        if (senderId == 0) {
            UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
            setUserInfo(userInfoBean);
            title.setText("我的信息");
            like.setText("更新");
            make_friend.setVisibility(View.GONE);
            one_to_one_chat.setVisibility(View.GONE);
            String avatarUrl = userInfoBean.getAvatarUrl();
            if (avatarUrl.contains("/")) {
                user_avatar.setImageBitmap(BitmapFactory.decodeFile(avatarUrl));
            } else {
                user_avatar.setImageResource(Integer.parseInt(userInfoBean.getAvatarUrl()));
            }

            like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(UserInfoActivity.this, UpdateInfoActivity.class);
                    startActivityForResult(intent, UPDATE_INFO_CODE);
                }
            });


        } else {


            String originAvatar = getIntent().getStringExtra("senderAvatar");
            String originSign = getIntent().getStringExtra("senderSign");
            UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject(senderId + "Info");


            friendApply = getIntent().getStringExtra("friendApply");

            int position = getIntent().getIntExtra("position", 0);

            if (friendApply != null) {

                make_friend.setText("拒绝");
                one_to_one_chat.setText("同意");

                make_friend.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MessageBean messageBean = new MessageBean();
                        messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
                        messageBean.setReceiverId(String.valueOf(userInfoBean.getId()));
                        messageBean.setStatus(0);
                        messageBean.setOneToOne(true);
                        Intent intent = new Intent();
                        intent.putExtra("status", 0);
                        intent.putExtra("position", position);
                        setResult(UPDATE_Friend_CODE, intent);
                        UserInfoRequest.dealFriendApply(new Gson().toJson(messageBean));

                        updateFriendApplyView(String.valueOf(userInfoBean.getId()), 0);

                        finish();
                    }
                });


                one_to_one_chat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent();
                        intent.putExtra("status", 1);
                        intent.putExtra("position", position);
                        setResult(UPDATE_Friend_CODE, intent);

                        MessageBean messageBean = new MessageBean();
                        messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
                        messageBean.setReceiverId(String.valueOf(userInfoBean.getId()));
                        messageBean.setStatus(1);
                        UserInfoBean myInfo = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
                        messageBean.setSenderAvatarPath(myInfo.getAvatarUrl());
                        messageBean.setOneToOne(true);
                        messageBean.setMsgType(10);
                        UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(@NonNull Message message) {

                                FriendListAdapter adapter = (FriendListAdapter) GlobalAssistMap.getObject("friendListAdapter");

                                UserInfoBean friendInfo = (UserInfoBean) GlobalAssistMap.getObject(String.valueOf(userInfoBean.getId()) + "Info");

                                if (adapter.friendBeanList == null) {
                                    adapter.friendBeanList = new ArrayList<>();
                                }
                                friendInfo.setLastMessage("你们已经成为朋友了~");
                                adapter.friendBeanList.add(friendInfo);
                                GlobalAssistMap.putObject(userInfoBean.getId() + "position", adapter.friendBeanList.size() - 1);

                                updateFriendApplyView(String.valueOf(userInfoBean.getId()), 1);

                                return true;
                            }
                        }), String.valueOf(userInfoBean.getId()));

                        UserInfoRequest.dealFriendApply(new Gson().toJson(messageBean));

                        finish();
                    }
                });


            } else {
                this.runOnUiThread(() -> {

                    if (GlobalAssistMap.getObject(userInfoBean.getId() + "position") != null) {
                        make_friend.setVisibility(View.GONE);
                        return;
                    }

                    String[] friends = userInfoBean.getFriends().split(",");
                    boolean isFriend = false;
                    for (String friendId : friends) {
                        if (friendId.equals(GlobalAssistMap.getObject("userId").toString())) {
                            make_friend.setVisibility(View.GONE);
                            isFriend = true;
                            break;
                        }
                    }

                    if (!isFriend) {
                        make_friend.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent();
                                intent.setClass(UserInfoActivity.this, AddFriendActivity.class);
                                intent.putExtra("friendId", String.valueOf(userInfoBean.getId()));
                                startActivity(intent);
                            }
                        });
                    }
                });
            }


            boolean avatarHasChange = !originAvatar.equals(userInfoBean.getAvatarUrl());
            String nickName = userInfoBean.getNickname();
            String sign = userInfoBean.getSign();
            sign = (sign == null || sign.equals("")) ? "" : ":" + sign;
            String mark = nickName + sign;
            mark = mark.length() > 22 ? mark.substring(0, 22) + "..." : mark;
            boolean signHasChange = false;
            if (originSign != null) {
                signHasChange = !originSign.equals(mark);
            }
            setUserInfo(userInfoBean);

            judgeNeedToUpdate(senderId, userInfoBean, avatarHasChange, signHasChange);
        }


    }


    private void setUserInfo(UserInfoBean userInfoBean) {
        user_id.getContentEdt().setText(String.valueOf(userInfoBean.getId()));
        user_nickname.getContentEdt().setText(userInfoBean.getNickname());
        user_age.getContentEdt().setText((userInfoBean.getAge() + "").equals("-1") ? "" : userInfoBean.getAge() + "");
        user_sex.getContentEdt().setText((userInfoBean.getSex() + "").equals("-1") ? "" : (userInfoBean.getSex() == 0 ? "女" : "男"));
        user_sign.getContentEdt().setText(userInfoBean.getSign());
        user_email.getContentEdt().setText(userInfoBean.getEmail());
        user_hobby.getContentEdt().setText(userInfoBean.getHobby());
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void judgeNeedToUpdate(int senderId, UserInfoBean userInfoBean, boolean avatarHasChange, boolean signHasChange) {
        final String[] avatarPath = {""};
        if (!userInfoBean.getAvatarUrl().contains("/")) {
            user_avatar.setBackgroundResource(Integer.parseInt(userInfoBean.getAvatarUrl()));
            if (avatarHasChange || signHasChange) {
                Intent intent = new Intent();
                if (avatarHasChange) {
                    intent.putExtra("avatarUpdate", senderId + "|" + userInfoBean.getAvatarUrl());
                }
                if (signHasChange) {
                    intent.putExtra("signUpdate", senderId);
                }
                if (friendApply == null) {
                    setResult(USER_INFO_CODE, intent);
                }
            }
        } else if (!avatarHasChange) {
            String userAvatarCache = (String) GlobalAssistMap.getObject(senderId + "Avatar");
            if (userAvatarCache != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(userAvatarCache);
                user_avatar.setImageBitmap(bitmap);
                if (signHasChange) {
                    Intent intent = new Intent();
                    intent.putExtra("signUpdate", senderId);
                    if (friendApply == null) {
                        setResult(USER_INFO_CODE, intent);
                    }
                }
            }
        } else {
            UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message message) {
                    if (Constant.SUCCESS.equals(message.obj)) {
                        avatarPath[0] = Constant.IMAGE_PATH + userInfoBean.getAvatarUrl().substring(userInfoBean.getAvatarUrl().lastIndexOf("/") + 1);
                        GlobalAssistMap.putObject(senderId + "Avatar", avatarPath[0]);
                        Bitmap bitmap = BitmapFactory.decodeFile(avatarPath[0]);
                        user_avatar.setImageBitmap(bitmap);

                        Intent intent = new Intent();
                        intent.putExtra("avatarUpdate", senderId + avatarPath[0]);

                        if (signHasChange) {
                            intent.putExtra("signUpdate", senderId);
                        }
                        if (friendApply == null) {
                            setResult(USER_INFO_CODE, intent);
                        }

                    }
                    return true;
                }
            }), userInfoBean.getAvatarServerPath());
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (data != null && resultCode == UPDATE_INFO_CODE) {
            if (data.getStringExtra("updateInfo") != null) {
                initView();
                if (GlobalAssistMap.getObject("avatarUpdate").equals("true")) {
                    Intent intent = new Intent();
                    setResult(UPDATE_INFO_CODE, intent);
                }

            }
        }
    }


    private void updateFriendApplyView(String userId, int status) {

        RecyclerView friendFunctionRecyclerView = (RecyclerView) GlobalAssistMap.getObject("friendFunctionRecyclerView");
        FriendMoreFunctionAdapter friendMoreFunctionAdapter = (FriendMoreFunctionAdapter) GlobalAssistMap.getObject("friendMoreFunctionAdapter");
        int index = 0;
        for (int i = 0; i < friendMoreFunctionAdapter.functionBeanList.size(); i++) {

            if (friendMoreFunctionAdapter.functionBeanList.get(i).getFunctionName().equals("好友申请")) {
                List<FriendApplyBean> applyList = friendMoreFunctionAdapter.functionBeanList.get(i).getApplyList();

                for (FriendApplyBean friendApplyBean : applyList) {
                    if (friendApplyBean.getApplyId().equals(userId)) {
                        friendApplyBean.setApplyStatus(String.valueOf(status));
                    }
                }

                index = i;
                break;
            }
        }

        View functionView = friendFunctionRecyclerView.getChildAt(index);
        TextView friendApply = functionView.findViewById(R.id.message_count);
        friendApply.post(new Runnable() {
            @Override
            public void run() {
                friendApply.setVisibility(View.GONE);
                String friendApplyCount = friendApply.getText().toString();
                if (friendApplyCount.equals("")) {
                    friendApplyCount = "";
                } else {
                    int num = Integer.parseInt(friendApplyCount);
                    if (num > 100) {
                        friendApplyCount = "99+";
                    } else {
                        friendApplyCount = String.valueOf(num - 1);
                    }
                }
                friendApply.setText(friendApplyCount);
            }
        });
    }

}
